How JavaScript Works

JavaScript, at its core, is a single-threaded language. This means it can only do one thing at a time. However, it handles complex tasks without freezing the browser using a model involving the JavaScript Engine, Call Stack, Web APIs, Callback Queue, and the Event Loop.

1. The JavaScript Engine & Execution Context

When you run JavaScript code, the JS Engine (like V8 in Chrome) creates a global execution context. This context has two phases:

2. The Call Stack

The Call Stack is a data structure that keeps track of function calls. When a function is called, it's added (pushed) to the top of the stack. When it returns, it's removed (popped) from the stack.

Call Stack Example

main()
first()
second()
function first() {
    console.log("Entering first()");
    second();
    console.log("Exiting first()");
}
function second() {
    console.log("  - Inside second()");
}
first(); // Start the process
        

3. Web APIs, Callback Queue, and Event Loop

What about asynchronous operations like setTimeout or fetching data? They don't block the call stack.

  1. When an async function (e.g., setTimeout) is called, it's passed to a Web API in the browser.
  2. The Call Stack continues running other code.
  3. Once the Web API finishes its task (e.g., the timer ends), it moves the callback function to the Callback Queue.
  4. The Event Loop constantly checks if the Call Stack is empty. If it is, it takes the first item from the Callback Queue and pushes it onto the Call Stack to be executed.
Call Stack
Event Loop
Callback Queue

Comparison Table

Concept Purpose Example
Call Stack Manages synchronous function execution (First-In, Last-Out). functionA() calls functionB().
Web API Handles browser-based async operations outside the JS engine. setTimeout, fetch(), DOM events.
Callback Queue Holds callback functions that are ready to be executed (First-In, First-Out). The function inside setTimeout waits here.
Event Loop Moves callbacks from the queue to the stack when the stack is empty. The "bridge" between async and sync.